package com.ruoyi.web.zbAdmin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mongodb.client.result.UpdateResult;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.zbAdmin.controller.param.CaiCompanyQuery;
import com.ruoyi.web.zbAdmin.domain.CaiCompanyQualificationDetailsList;
import com.ruoyi.web.zbAdmin.domain.CaiCompanyRegisteredPersonnelDetailsList;
import com.ruoyi.web.zbAdmin.domain.CaiQualiCompany;
import com.ruoyi.web.zbAdmin.mapper.CaiZhaobiaoPropertyMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 招标属性
 * @author liandyao
 * @date 2022/12/15 10:47
 */
@Api(tags="2001 企业查询")
@RestController
@RequestMapping("/zbApi/company")
@Slf4j
public class CaiCompanyController extends BaseController {

    @Autowired
    private CaiZhaobiaoPropertyMapper userMapper;

    public static final String collectionName = "cai_quali_company";

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户列表
     */
    @ApiOperation("企业详情列表")
    @GetMapping("/list")
    public TableDataInfo list(CaiCompanyQuery userQuery) {

        log.info("=====>"+JSONUtil.toJsonStr(userQuery));
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();

        Query query = new Query();
        if(StrUtil.isNotBlank(userQuery.getCompanyName())){
            query.addCriteria(Criteria.where("companyName").is(userQuery.getCompanyName()));
        }

        if(StrUtil.isNotBlank(userQuery.getProvinceName())){
            query.addCriteria(Criteria.where("companyProvince").is(userQuery.getProvinceName()));
        }

        if(StrUtil.isNotBlank(userQuery.getCityName())){
            query.addCriteria(Criteria.where("companyCity").is(userQuery.getCityName()));
        }

        // 设置起始页和每页查询条数
        Pageable pageable = PageRequest.of(userQuery.getCurPage(), userQuery.getPageSize(), Sort.by(Sort.Order.desc("companyRegCapitalAmount")));
        // 查询记录总数
        long totalCount = mongoTemplate.count(query,collectionName);
        //查询分页后的记录
        List<CaiQualiCompany> result = mongoTemplate.find(query.with(pageable), CaiQualiCompany.class, collectionName);

        return TableDataInfo.success(result,totalCount);
    }




    @ApiOperation("获取企业详情信息")
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable String id) {
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        CaiQualiCompany user = mongoTemplate.findById(id,CaiQualiCompany.class,collectionName);
        if(user==null){
            return AjaxResult.error("不存在!");
        }
        return AjaxResult.success("成功",user);
    }


    @ApiOperation("更新详情")
    @PostMapping("/update")
    public AjaxResult update(CaiQualiCompany user, HttpServletRequest request) {
        String _id = request.getParameter("_id");
        user.set_id(_id);
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        log.info("===>"+ JSONUtil.toJsonStr(user));
        if (StringUtils.isNull(user) || StringUtils.isNull(user.get_id())) {
            return AjaxResult.success("ID为空");
        }
        Document doc = new Document();
        //字段中会加上_class,该方法是为了去掉_class
        MappingMongoConverter mappingConverter =  (MappingMongoConverter)mongoTemplate.getConverter();
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));

        mongoTemplate.getConverter().write(user, doc);
        Update update = Update.fromDocument(doc);

        UpdateResult re = this.userMapper.getMongoTemplate().upsert(Query.query(Criteria.where("_id").is(user.get_id())),update,collectionName);

        return AjaxResult.success("修改成功",re.getMatchedCount());


    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {

        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        /**
         * 删除这条招标相关的所有信息
         */
        Update propertyTable = Update.update("delFlag", CaiQualiCompany.IS_DEL_YES).set("operation", getUsername() +DateUtil.now()+ "-删除").set("updateTime", DateUtil.now());
        UpdateResult result=mongoTemplate.upsert(Query.query(Criteria.where("_id").is(id)), propertyTable,collectionName);


        return AjaxResult.success("删除成功",result.getMatchedCount());

    }


    @ApiOperation("查询该企业的资质信息")
    @PostMapping("/showQualification/{id}")
    public AjaxResult showQualification(@PathVariable String id){
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        List<CaiCompanyQualificationDetailsList> list = mongoTemplate.find(Query.query(Criteria.where("companyCid").is(id)), CaiCompanyQualificationDetailsList.class, "cai_companyQualificationDetailsList");
        return AjaxResult.success("成功",list);
    }

    @ApiOperation("查询该企业的注册人员信息")
    @PostMapping("/showRegistPerson/{id}")
    public AjaxResult showRegistPerson(@PathVariable String id){
        MongoTemplate mongoTemplate = this.userMapper.getMongoTemplate();
        List<CaiCompanyRegisteredPersonnelDetailsList> list = mongoTemplate.find(Query.query(Criteria.where("companyCid").is(id)), CaiCompanyRegisteredPersonnelDetailsList.class, "cai_companyRegisteredPersonnelDetailsList");
        return AjaxResult.success("成功",list);
    }

}
